/*
 * jngc, Java utility classes by Nicholas Coltharp
 * Copyright (C) 2010 Nicholas Coltharp <ngc1@rice.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.rice.ngc1.util.iterable;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Adapts a {@link CharSequence} for the Java iterator API.
 */
public class StringIterator implements Iterable<Character> {

    /**
     * The sequence of characters that this object's iterators iterate
     * over.
     */
    private final CharSequence str;

    /**
     * Constructs a new {@code StringIterator} which will iterate over
     * the given char sequence.
     * 
     * @param str
     *            the {@code CharSequence} to iterate over
     */
    public StringIterator(CharSequence str) {
        this.str = str;
    }

    /**
     * Returns an iterator which will iterate over the char sequence
     * provided at construction time. Calls to
     * {@link Iterator#remove()} will result in an
     * {@link UnsupportedOperationException} being thrown.
     * 
     * @return an iterator for this object's char sequence
     */
    @Override
    public Iterator<Character> iterator() {
        return new Iterator<Character>() {

            private int index = 0;

            @Override
            public boolean hasNext() {
                return (index < str.length());
            }

            @Override
            public Character next() {
                if (!hasNext()) {
                    throw new NoSuchElementException("no more elements");
                }
                return str.charAt(index++);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("cannot "
                        + "remove characters from a char sequence");
            }
        };
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("StringIterator(");
        builder.append(str);
        builder.append(")");
        return builder.toString();
    }
}
